import { useEffect, useState } from "react";
import { Vector3Tuple } from "three";

const defaultConfig: Config = {
  tone: {
    toneMapping: "No",
    exposure: 1,
  },
  points1: [],
  points2: [],
  crystals: [],
  otherSetting: {
    activeDis1: 5,
    activeDis2: 6,
  },
};

/**
 * 获取配置文件
 */

let cachedConfig: Config | null = null;

export async function preloadConfig() {
  if (!cachedConfig) {
    const res = await fetch("./config.json");
    cachedConfig = (await res.json()) as Config;
  }
}

export function useConfig() {
  const [config, setConfig] = useState<Config>(defaultConfig);

  useEffect(() => {
    if (cachedConfig) {
      setConfig(cachedConfig);
    } else {
      preloadConfig().then(() => setConfig(cachedConfig!));
    }
  }, []);

  return config;
}
type Config = {
  tone: {
    toneMapping: keyof typeof ToneMap;
    exposure: number;
  };
  points1: Point[];
  points2: Point[];
  crystals: CrystalProp[];
  otherSetting: {
    activeDis1: number;
    activeDis2: number;
  };
};

export type CrystalProp = {
  id: number;
  name: string;
  rotation: Vector3Tuple;
  position: Vector3Tuple;
  scale: number;
};
export type Point = {
  id: number;
  name: string;
  path: string;
  texture?: string;
  position?: Vector3Tuple;
  rotation?: Vector3Tuple;
  scale?: number | Vector3Tuple;
};
export enum ToneMap {
  No,
  Linear,
  Reinhard,
  Cineon,
  ACESFilmic,
  Custom,
  AgX,
}
